import Vue from 'vue';
import Request from "@/sdk/pocky-request/index.js"; //引入
import COMM from "@/common/common.js";
import idfa from "@/js_sdk/dc-idfa/idfa.js";
var vm = new Vue();
/**
 * 消息推送 push
 */
const push = {
	// 状态
	state: {
		pushMsg: {}, //推送消息
		pushId: '',
		imei: '',
	},
	// 内部派生
	getters: {

	},
	// 同步方法 commit
	mutations: {
		pushId: (state, payload) => {
			state.pushId = payload
		},
		imei: (state, payload) => {
			state.imei = payload
		},
		pushMsg: (state, payload) => {
			plus.push.createMessage(payload.content, payload.payload, {
				title: payload.title,
				delay: 0,
				sound: 'system', //提示音
				cover: false, //不覆盖
			})
			state.pushMsg = payload
		}
	},
	// 异步方法 dispatch
	actions: {
		// 监听收到 push消息
		listenPush(context) {
			let _this = this;
			plus.push.addEventListener("receive", function(msg) {
				console.log("push收取：");
				console.log(msg);
				// iphone 在已打开APP的情况下,通知栏不会弹出消息框,此时需要本地创建一条通知
				if(uni.getSystemInfoSync().platform=='ios'){
					if (msg.hasOwnProperty('type') && msg.type != 'click') {
						_this.commit("pushMsg", {
							title: msg.title,
							content: msg.content,
							payload: msg.payload.param?msg.payload.param:''
						})
					}
				}else{
					setTimeout(()=>{
						if (msg.payload) { //如果透传消息带参数
							vm.toPage({
								url: msg.payload
							});
						}
					},500)
					
				}
			})
		},
		// 监听push消息点击
		listenPushTap(context) {
			plus.push.addEventListener("click", function(msg) {
				console.log("push点击：");
				console.log(msg);
				if (uni.getSystemInfoSync().platform == 'ios') {
					if (msg.payload.param) { //如果透传消息带参数
						setTimeout(()=>{
							vm.toPage({
								url: msg.payload.param
							});
						},500)
						
					}else if(msg.payload){
						setTimeout(()=>{
							vm.toPage({
								url: msg.payload
							});
						},500)
					}
				} else {
					if (msg.payload) { //如果透传消息带参数
						setTimeout(()=>{
							vm.toPage({
								url: msg.payload
							});
						},500)
						
					}
				}

			})
		},
		/**
		 * @description  获取推送相关IMEI和cid
		 * @param {Object} context
		 */
		getPushId(context) {
			let clienInfo = plus.push.getClientInfo();
			let _imei = '';
			if (uni.getSystemInfoSync().platform == 'android') {
				if (plus.device.imei.indexOf(',') > 0) {
					_imei = plus.device.imei.split(',')[0]
				} else {
					_imei = plus.device.imei
				}

			} else {
				_imei = idfa.value();
			}

			this.commit('pushId', clienInfo.clientid);
			this.commit('imei', _imei);
		}

	}
}

export default push
